package payment

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/utils/database"
)

// TransactionType 交易类型常量
const (
	TransactionTypeMatrixTransfer = "matrix_transfer"
	TransactionTypeCardRecharge   = "card_recharge"
	TransactionTypeCardPayment    = "card_payment"
	TransactionTypeCardRefund     = "card_refund"
)

// TransactionStatus 交易状态常量
const (
	TransactionStatusCompleted = "completed"
	TransactionStatusPending   = "pending"
	TransactionStatusFailed    = "failed"
)

// TransactionRecord 交易记录结构
type TransactionRecord struct {
	TransactionID   string          `json:"transaction_id"`
	CardID          string          `json:"card_id"`
	TransactionType string          `json:"transaction_type"`
	Amount          float64         `json:"amount"`
	Currency        string          `json:"currency"`
	Status          string          `json:"status"`
	MatrixAccount   string          `json:"matrix_account"`
	Platform        string          `json:"platform"`
	RawData         json.RawMessage `json:"raw_data"`
	ProcessedAt     time.Time       `json:"processed_at"`
}

// RecordTransaction 记录交易信息到数据库
// prefix: 交易ID前缀，如 "MT" 表示矩阵转账
// cardID: 卡ID，如果是系统操作可以使用 "SYSTEM"
// transactionType: 交易类型，使用 TransactionType 常量
// amount: 交易金额
// currency: 货币类型
// status: 交易状态，使用 TransactionStatus 常量
// matrixAccount: 矩阵账户
// platform: 平台名称
// rawData: 原始响应数据
func RecordTransaction(
	prefix string,
	cardID string,
	transactionType string,
	amount float64,
	currency string,
	status string,
	matrixAccount string,
	platform string,
	rawData interface{},
) (*TransactionRecord, error) {
	// 生成交易ID
	transactionID := fmt.Sprintf("%s%s", prefix, time.Now().Format("20060102150405"))

	// 将原始数据转换为JSON
	rawDataBytes, err := json.Marshal(rawData)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal raw data: %v", err)
	}

	// 创建交易记录
	record := &TransactionRecord{
		TransactionID:   transactionID,
		CardID:          cardID,
		TransactionType: transactionType,
		Amount:          amount,
		Currency:        currency,
		Status:          status,
		MatrixAccount:   matrixAccount,
		Platform:        platform,
		RawData:         rawDataBytes,
		ProcessedAt:     time.Now(),
	}

	// 插入交易记录
	insertSQL := `
		INSERT INTO transactions (
			transaction_id, card_id, transaction_type, amount, currency,
			status, matrix_account, platform, raw_data, processed_at
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	`
	if err := database.UpdateDatabaseWithSQL(
		insertSQL,
		record.TransactionID,
		record.CardID,
		record.TransactionType,
		record.Amount,
		record.Currency,
		record.Status,
		record.MatrixAccount,
		record.Platform,
		record.RawData,
		record.ProcessedAt,
	); err != nil {
		return nil, fmt.Errorf("failed to record transaction: %v", err)
	}

	return record, nil
}
